package com.mall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.common.dto.OrderNoteDto;
import com.mall.common.page.PageData;
import com.mall.common.service.impl.CrudServiceImpl;
import com.mall.payment.dao.PaymentDao;
import com.mall.payment.entity.PaymentEntity;
import com.mall.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.UUID;

/**
 * @author: 谢君臣
 * @Date: 2022/6/24-14:51
 * @version: 1.0
 * @function:
 */
@Service
@Slf4j
public class PaymentServiceImpl extends CrudServiceImpl<PaymentDao, PaymentEntity, PaymentEntity> implements PaymentService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public QueryWrapper<PaymentEntity> getWrapper(Map<String, Object> params) {
        String id = (String)params.get("id");

        QueryWrapper<PaymentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public PageData<PaymentEntity> findAll(Map<String, Object> params) {
        PageData<PaymentEntity> pageData = this.page(params);
        return pageData;
    }

    @Override
    public PaymentEntity getPaymentByTransactionId(String transactionId) {
        QueryWrapper<PaymentEntity> queryWrapper = new QueryWrapper<PaymentEntity>().eq("transaction_id", transactionId);
        return baseDao.selectOne(queryWrapper);
    }

    @Transactional
    @Override
    public void updateStatus(PaymentEntity payment) {
        int i = baseDao.updateById(payment);
        if (i<1) {
            throw new RuntimeException("更新支付数据异常");
        }
        log.info("支付回调成功");
        // 发送减库存消息
        String orderSn = payment.getOrderId();
        OrderNoteDto noteDto = new OrderNoteDto(orderSn);
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        ReturnedMessage returnedMessage = new ReturnedMessage(
                new Message(
                        JSON.toJSONBytes(noteDto)),
                200,
                "com.mall.common.dto.OrderNoteDto",
                "order-event-exchange",
                "order.success.other");
        correlationData.setReturned(returnedMessage);
        rabbitTemplate.convertAndSend("order-event-exchange","order.success.other",noteDto,correlationData);
    }


}
